package com.funmi.lizip.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.Camera;
import com.funmi.lizip.entity.Photo;
import com.funmi.lizip.entity.dto.photo.*;
import com.funmi.lizip.entity.vo.CPVo;
import com.funmi.lizip.entity.vo.PhotoVo;
import com.funmi.lizip.entity.vo.StatisticsAllVo;
import com.funmi.lizip.entity.vo.StatisticsPhotoVo;
import com.funmi.lizip.service.CameraService;
import com.funmi.lizip.service.PhotoLogService;
import com.funmi.lizip.service.PhotoService;
import com.funmi.lizip.utils.MyJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yeyg
 * @since 2022-11-02
 */
@Api(tags = "红外照片模块")
@RestController
@RequestMapping("/infraredPhoto")
public class PhotoController {

    @Autowired
    private PhotoService photoService;
    @Autowired
    private PhotoLogService photoLogService;
    @Autowired
    private CameraService cameraService;

    /**
     * 单张导入
     * */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "上传图片后新增照片")
    @PostMapping("")
    public R infraredPhoto(@RequestBody PhotoAddRequest request) throws IOException {
        boolean b = photoService.insert(request);
        if (b){
            return R.success().data("图片上传成功");
        }
        return R.success().data("图片上传失败");
    }


    /**
     * 统计分析展示
     * */
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "通过id 获取红外照片与相机详情")
    @GetMapping("/{id}")
    public R getPhoto(@PathVariable int id){
        Photo photo = photoService.getById(id);
        photo.setFileName("CameraPhoto"+"/"+photo.getFileName());
        QueryWrapper<Camera> cameraQueryWrapper = new QueryWrapper<>();
        cameraQueryWrapper.eq("id", photo.getCameraId());
        Camera camera = new Camera();
        Camera one = cameraService.getOne(cameraQueryWrapper);
        if (!ObjectUtils.isEmpty(one)){
            camera = one;
        }
        CPVo cpVo = new CPVo(camera, photo);
        return R.success().data(cpVo);
    }



    /**
     * 手动修改红外图片
     * 可修改物种类型 animal_type,动物行为，动物数量，动物种类
     * */
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改图片")
    @PutMapping("/{id}")
    public R updateById(@RequestBody(required = false) PhotoUpdateRequest request, @PathVariable int id){
        Boolean aBoolean = photoService.updateById(id, request);
        if (aBoolean){
            return R.success().data("修改成功");
        }
        return R.success().data("修改失败");
    }


    /**
     * 照片物种识别
     * */

    /**
     * 无效照片筛选
     * */
    @ApiOperation(value = "手动标记无效红外图片")
    @PutMapping("")
    public R infraredPhoto(@RequestBody HashMap<String, ArrayList<Integer>> id){
        return photoService.updateValid(id);
    }

    private Camera one;
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "根据输入进行检索")
    @GetMapping("")
    public R queryList(PhotoQueryRequest request) throws IllegalAccessException {
        long current = 1;
        long size = 10;
        Photo photoQuery = new Photo();
        if (request != null){
            PhotoQueryRequest photoQueryRequest = MyJsonUtil.setNullValue(request);
            BeanUtils.copyProperties(photoQueryRequest, photoQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        photoQuery.setCameraId(null);
        one = null;
        QueryWrapper<Photo> queryWrapper = new QueryWrapper<>(photoQuery);
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getPointNo())){
            QueryWrapper<Camera> cameraQueryWrapper = new QueryWrapper<>();
            cameraQueryWrapper.like("point_no", request.getPointNo());
            List<Camera> list = cameraService.list(cameraQueryWrapper);
            //one = cameraService.getOne(cameraQueryWrapper);
            if (ObjectUtils.isEmpty(list)){
                return R.success().message("没有照片");
            }
            List<Integer> collect = list.stream().map(Camera::getId).collect(Collectors.toList());
            queryWrapper.in("camera_id", collect);
        }
        if (request != null){
            queryWrapper.between("shot_at",
                    (request.getStartAt() == null)? (LocalDateTime.of(2000, 10, 12, 6, 30)): request.getStartAt(),
                    (request.getEndAt() == null)? (LocalDateTime.now()):request.getEndAt());
        }
        queryWrapper.orderByDesc("shot_at");
        Page<Photo> photoPage = photoService.page(new Page<>(current, size), queryWrapper);

        Page<PhotoVo> photoVoPage = new PageDTO(photoPage.getCurrent(), photoPage.getSize(), photoPage.getTotal());
        List<PhotoVo> photoVoList = photoPage.getRecords().stream().map(photo -> {
            PhotoVo photoVo = new PhotoVo();
            BeanUtils.copyProperties(photo, photoVo);
            photoVo.setPointNo(cameraService.getById(photo.getCameraId()).getPointNo());
            // 拼接图片地址
            photoVo.setFileName("CameraPhoto"+"\\"+photo.getFileName());
            return photoVo;
        }).collect(Collectors.toList());
        photoVoPage.setRecords(photoVoList);
        return R.success().data(photoVoPage);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "图片统计分析")
    @GetMapping("/statistics")
    public R tongji(PhotoSQueryRequest request){
        StatisticsPhotoVo statisticsPhotoVo = photoService.getStatistics(request);
        return R.success().data(statisticsPhotoVo);
    }
}

